<template>
  <div id="app">
    <keep-alive>
      <router-view v-if="showView" />
    </keep-alive>
  </div>
</template>
<script>
import { httpConfig, httpSetLogin } from "@/api/user";
import { getToken } from "@/utils/auth";
import { WEBIM } from "@/utils/old/webim";
import { busService } from "@/service/busService";
import { AppConfig } from "@/utils/old/appconfig";
import { eventConst } from "@/utils/my/const/eventConst";
import { imSdk } from "@/utils/old/websocket_sdk";
import { appUtils } from "@/utils/my/appUtils";

export default {
  name: "App",
  data() {
    return {
      // 用于点击当前页的router时，刷新当前页
      showView: true
    };
  },
  beforeCreate() {},

  created() {
    let that = this;
    //获取配置信息
    httpConfig(function() {
      //不存在登录信息， 且非登录页， 进入登录页， 监听登录成功
      if (!that.$store.state.user.account) {
        that.$router.push({
          path: "/login"
        });
      }
    });

    busService.on("login-success", function(userInfo) {
      that.connect();
    });

    busService.on("init-success", function() {
      if ("/index/message" != that.$route.path) {
        that.$router.push("/index/message");
      }
      // that.$store.commit('reset_chat', null)
    });

    busService.on("go-login", function() {
      that.$store.commit("clear_login");
      that.$store.dispatch("ACT_USER_LOGOUT");
      // that.$router.push({
      //   path: "/login"
      // });
    });

    busService.on(eventConst.connect, function() {
      that.$store.commit("init_data");
      that.$store.commit("UPDATE_SOCKET_STATUS", true);
      imSdk.lockReconnect = false;
    });
  },
  methods: {
    connect() {
      let that = this;
      WEBIM.initWebIM(
        AppConfig.websocketUrl,
        this.$store.state.user.userId,
        appUtils.getEnv(),
        getToken(),
        AppConfig.keepalive,
        this.$store.state.user.nickname
      );

      httpSetLogin().then(({ resultCode, data }) => {
        if (resultCode) {
          // var logoutTime = DataUtils.getLogoutTime();
          // console.log("autoLogin " + JSON.stringify(result));
          // myData.nickname = result.nickname;
          // myData.settings = result.settings;
          // myData.multipleDevices = result.settings.multipleDevices;
          // if (1 == myData.multipleDevices)
          //     myData.resource = "web";
          // myData.jid = store.state.user.userId + "/" + myData.resource;
          try {
            WEBIM.loginIM();
          } catch (ex) {
            console.log(ex);
          }
        }
      });
    },

    // 刷新当前路由方法
    refreshView() {
      this.showView = false;
      this.$nextTick(() => (this.showView = true));
    }
  }
};
</script>
